"""摄像头管理器 - 统一管理摄像头资源"""
import cv2
from PyQt6.QtCore import QTimer
from PyQt6.QtGui import QImage, QPixmap


class CameraManager:
    """统一管理摄像头资源的类"""
    
    def __init__(self):
        self.cap = None
        self.timer = None
        self.is_running = False
        self.frame_callback = None
        
    def start_camera(self, frame_callback=None):
        """启动摄像头"""
        if self.is_running:
            self.stop_camera()
            
        self.cap = cv2.VideoCapture(0)
        if not self.cap.isOpened():
            raise RuntimeError("无法打开摄像头")
            
        self.frame_callback = frame_callback
        self.timer = QTimer()
        self.timer.timeout.connect(self._update_frame)
        self.timer.start(30)  # 30ms间隔，约33fps
        self.is_running = True
        
    def stop_camera(self):
        """停止摄像头"""
        try:
            if self.timer is not None:
                self.timer.stop()
                self.timer = None
        except Exception:
            pass
            
        try:
            if self.cap is not None:
                self.cap.release()
                self.cap = None
        except Exception:
            pass
            
        self.is_running = False
        self.frame_callback = None
        
    def _update_frame(self):
        """更新帧数据"""
        if not self.cap or not self.cap.isOpened():
            return
            
        ret, frame = self.cap.read()
        if not ret:
            return
            
        # 水平翻转图像（镜像效果）
        frame = cv2.flip(frame, 1)
        
        # 如果有回调函数，调用它处理帧
        if self.frame_callback:
            frame = self.frame_callback(frame)
            
        # 转换为Qt可显示的格式
        rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        h, w, ch = rgb_frame.shape
        bytes_per_line = ch * w
        qimg = QImage(rgb_frame.data, w, h, bytes_per_line, QImage.Format.Format_RGB888)
        
        return QPixmap.fromImage(qimg)
        
    def get_current_frame_rgb(self):
        """获取当前帧的RGB格式"""
        if not self.cap or not self.cap.isOpened():
            return None
            
        ret, frame = self.cap.read()
        if not ret:
            return None
            
        frame = cv2.flip(frame, 1)
        return cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        
    def get_current_frame_gray(self):
        """获取当前帧的灰度格式"""
        rgb_frame = self.get_current_frame_rgb()
        if rgb_frame is None:
            return None
            
        return cv2.cvtColor(rgb_frame, cv2.COLOR_RGB2GRAY)
        
    def __del__(self):
        """析构函数，确保资源被释放"""
        self.stop_camera()